/** @namespace app.model.Config */
const _ = require('lodash');
module.exports = app => {
  const {STRING, JSON} = app.Sequelize;

  const Config = app.model.define('config', {
    key: {type: STRING, unique: 'key', allowNull: false},
    value: {type: JSON, allowNull: false},
  }, {timestamps: false});

  /**
   * 添加记录
   * @param key
   * @param defaultValue
   * @returns {Promise<*>}
   */
  Config.get = async (key, defaultValue = null) => {
    if (_.isString(key)) {
      const result = await Config.findOne({where: {key}});
      if (!result)
        return defaultValue;
      return result.value;
    } else if (_.isArray(key)) {
      let kv = await Config.findAll(
          {where: {key: {[app.Sequelize.Op.in]: key}}});
      if (_.isEmpty(kv))
        return defaultValue;
      const result = {};
      kv.forEach(v => {
        result[v.key] = v.value;
      });
      return result;
    }
  };

  /**
   * 更新记录
   * @param key
   * @param value
   * @returns {Promise<void>}
   */
  Config.set = async (key, value) => {
    if (key.hasOwnProperty('key') && key.hasOwnProperty('value')) {
      await Config.upsert(key);
    } else {
      await Config.upsert({key, value});
    }
  };

  /**
   * 删除记录
   * @param key
   * @returns {Promise<void>}
   */
  Config.destroy = async key => {
    await Config.destroy({key});
  };

  return Config;
};